'use strict';

/**
 * @ngdoc function
 * @name sfhtHaitaoCmsApp.controller:PageManagerCtrl
 * @description
 * # PageManagerCtrl
 * Controller of the sfhtHaitaoCmsApp
 */
angular.module('sfhtHaitaoCmsApp')
  .controller('ModuleHeaderConfigCtrl', function($scope, $modal, $log, HeaderServiceConfig) {
    var DEFAULT_PAGE_SIZE = 25;
    $scope.pages = [];
    $scope.totalItems = 1;
    $scope.currentPage = 1;

    var HeaderServiceConfig = HeaderServiceConfig.getInstance();

    $scope.search = function() {
      $scope.currentPage = 1;
      getHeaderConfig($scope.topType, $scope.currentPage);
    };

    $scope.init = function() {
      if (typeof $scope.topType == "undefined" || $scope.topType == null || $scope.topType == "") {
        $scope.topType = 1;
      }
      getHeaderConfig($scope.topType, $scope.currentPage)
    };

    $scope.pageChanged = function() {
      getHeaderConfig($scope.topType, $scope.currentPage)
    };

    var getHeaderConfig = function(topType, pageIndex) {
      var pagedQueryOption = {
        pageIndex: pageIndex,
        pageSize: DEFAULT_PAGE_SIZE
      };
      HeaderServiceConfig.getHeaderConfig(topType, pagedQueryOption)
        .then(function(data) {
          $scope.pages = data.cmsHeaderConfigs;
          $scope.totalItems = data.pageInfo.totalCount;
          $scope.currentPage = data.pageInfo.pageIndex;
        });
    };

    $scope.open = function(page) {
      var modal = $modal.open({
        animation: true,
        templateUrl: 'header.config.edit.html',
        controller: 'ModuleHeaderConfigEditCtrl',
        size: 'lg',
        resolve: {
          page: function() {
            return page;
          }
        }
      });
      modal.result.then(function(data) {
        item.version = data.value;
      }, function(data) {

      });
    }

    $scope.getTopType = function(topType) {
      if (topType == "0") {
        return "公告";
      }
      if (topType == "1") {
        return "顶通";
      }
    };

    var pageType = {
      "1": "首页",
      "2": "频道页",
      "3": "搜索页&店铺",
      "4": "活动页",
      "5": "个人中心",
      "6": "订单",
      "7": "详情页&购物车",
    };
    $scope.getType = function(dispageType) {
      return pageType[dispageType];
    };

    $scope.add = function() {
      var modal = $modal.open({
        animation: true,
        templateUrl: 'header.config.add.html',
        controller: 'ModuleHeaderConfigAddCtrl',
        size: 'lg',
        resolve: {}
      });
      modal.result.then(function(data) {}, function(data) {});
    }

  })
  .controller('ModuleHeaderConfigEditCtrl', function($scope, $route, $modal, store, $modalInstance, $log, page, CONST_UPLOAD_LIMIT, CONST_CMS_REQUEST_URL_FILE, uiUploader, HeaderServiceConfig) {
    var HeaderServiceConfig = HeaderServiceConfig.getInstance();
    var temDate = new Date(page.startTime);

    var uploader = function(uploadfile, index) {
      uiUploader.startUpload({
        url: CONST_CMS_REQUEST_URL_FILE,
        concurrency: 1,
        onProgress: function(file) {
          $scope.$apply();
        },
        onCompleted: function(file, response) {
          var res = JSON.parse(response);
          var arr = _.values(res.content[0]);
          uploadfile = arr[0];
          if (index == "1") {
            $scope.page.imgUrl = arr[0];
            $scope.isCompleted = true;
          } else {
            $scope.page.bigImgUrl = arr[0];
            $scope.isCompletedB = true;
          }

          $scope.$digest();
        },
        onCompletedAll: function(files) {
          $('#fileuploader').off('change');
        }
      });
    };
    $scope.changeFile = function(index) {
      $('#fileuploader').on('change', function(e) {
        var files = e.target.files;
        if (files) {
          var isBelow2M = false;
          var isAllowFile = true;
          _.each(files, function(file) {
            isBelow2M = isBelow2M || (file.size > CONST_UPLOAD_LIMIT);
            isAllowFile = isAllowFile && /(.jpg|.png|.jpeg|.gif|.bmp)$/.test(file.name)
          });
          if (isBelow2M && !isAllowFile) {
            return setTimeout(function() {
              alert('文件类型不匹配并且大于2M无法上传！');
            }, 0);
          } else if (isBelow2M && isAllowFile) {
            return setTimeout(function() {
              alert('文件大于2M无法上传！');
            }, 0);
          } else if (!isBelow2M && !isAllowFile) {
            return setTimeout(function() {
              alert('文件类型不匹配无法上传！');
            }, 0);
          }
        }

        uiUploader.addFiles(files);
        if (index == "1") {
          uploader($scope.page.imgUrl, index);
        } else {
          uploader($scope.page.bigImgUrl);
        }
      });

      $('#fileuploader').trigger('click')
    };

    function convertDateToString(value) {
      var returnValue = "";
      if (value) {
        var dateValue = new Date(value);
        returnValue = dateValue.getFullYear() + "-" + (dateValue.getMonth() + 1) + "-" + dateValue.getDate() + " " + dateValue.getHours() + ":" + dateValue.getMinutes();
      }
      return returnValue;
    }

    page.startTime = convertDateToString(page.startTime);
    page.endTime = convertDateToString(page.endTime);
    $scope.page = page;
    //日历
    $scope.initTime = function() {
      $('.datetimepicker').datetimepicker({
        format: 'YYYY-MM-DD HH:mm'
      })
    };

    $scope.dateChange = function(index) {
      if (index == "1") {
        $scope.page.startTime = $('.datetimepicker' + index).val();
      } else {
        $scope.page.endTime = $('.datetimepicker' + index).val();
      }
    }

    $scope.changeTopType = function(topType) {
      if (topType == "" || topType == null) {
        $scope.page.topType = 0;
      }
    }

    $scope.save = function(page) {
      if (page.startTime != null) {
        page.startTime = new Date(page.startTime).getTime();
      }
      if (page.endTime != null) {
        page.endTime = new Date(page.endTime).getTime();
      }
      HeaderServiceConfig.updateHeaderConfig(page)
        .then(function(data) {
          if (data.value > 0) {
            $modalInstance.close();
            $route.reload();
            // window.location.reload();
          } else {
            alert("修改失败！！");
          }
        }, function(data) {
          alert(data);
        });

    }

    $scope.cancel = function() {
      $modalInstance.dismiss("cancel");
    }

  })
  .controller('ModuleHeaderConfigAddCtrl', function($scope, $modal, store, $modalInstance, CONST_UPLOAD_LIMIT, CONST_CMS_REQUEST_URL_FILE, uiUploader, $log, HeaderServiceConfig) {
    var HeaderServiceConfig = HeaderServiceConfig.getInstance();
    $scope.page = {};
    $scope.page.cascadeType = 0;

    var uploader = function(uploadfile, index) {
      uiUploader.startUpload({
        url: CONST_CMS_REQUEST_URL_FILE,
        concurrency: 1,
        onProgress: function(file) {
          $scope.$apply();
        },
        onCompleted: function(file, response) {
          var res = JSON.parse(response);
          var arr = _.values(res.content[0]);
          uploadfile = arr[0];
          if (index == "1") {
            $scope.page.imgUrl = arr[0];
            $scope.isCompleted = true;
          } else {
            $scope.page.bigImgUrl = arr[0];
            $scope.isCompletedB = true;
          }

          $scope.$digest();
        },
        onCompletedAll: function(files) {
          $('#fileuploader').off('change');
        }
      });
    };
    $scope.changeFile = function(index) {
      $('#fileuploader').on('change', function(e) {
        var files = e.target.files;
        if (files) {
          var isBelow2M = false;
          var isAllowFile = true;
          _.each(files, function(file) {
            isBelow2M = isBelow2M || (file.size > CONST_UPLOAD_LIMIT);
            isAllowFile = isAllowFile && /(.jpg|.png|.jpeg|.gif|.bmp)$/.test(file.name)
          });
          if (isBelow2M && !isAllowFile) {
            return setTimeout(function() {
              alert('文件类型不匹配并且大于2M无法上传！');
            }, 0);
          } else if (isBelow2M && isAllowFile) {
            return setTimeout(function() {
              alert('文件大于2M无法上传！');
            }, 0);
          } else if (!isBelow2M && !isAllowFile) {
            return setTimeout(function() {
              alert('文件类型不匹配无法上传！');
            }, 0);
          }
        }

        uiUploader.addFiles(files);
        if (index == "1") {
          uploader($scope.page.imgUrl, index);
        } else {
          uploader($scope.page.bigImgUrl);
        }
      });

      $('#fileuploader').trigger('click')
    };

    $scope.init = function() {
      $scope.page.topType = 1;
      $scope.page.displayPage = 1;
    };
    //日历
    $scope.initTime = function() {
      $('.datetimepicker').datetimepicker({
        format: 'YYYY-MM-DD HH:mm'
      })
    };

    $scope.dateChange = function(index) {
      if (index == "1") {
        $scope.page.startTime = $('.datetimepicker' + index).val();
      } else {
        $scope.page.endTime = $('.datetimepicker' + index).val();
      }
    }

    $scope.changeTopType = function(topType) {
      if (topType == "" || topType == null) {
        $scope.page.topType = 0;
      }
    }

    var getPageType = function() {
      var typeValue = "";
      var i = 0;
      var typelist = $("[name='pageType']");
      _.each(typelist, function(value) {
        if ($(value).is(':checked')) {
          if (i > 0) {
            typeValue = typeValue + ",";
          }
          typeValue = typeValue + $(value).val();
          i = i + 1;
        }
      });
      return typeValue;
    };

    $scope.save = function(page) {
      page.displayPage = getPageType();
      if (page.startTime != null) {
        page.startTime = new Date(page.startTime).getTime();
      }
      if (page.endTime != null) {
        page.endTime = new Date(page.endTime).getTime();
      }
      HeaderServiceConfig.createHeaderConfig(page)
        .then(function(data) {
          if (data.value == 1) {
            $modalInstance.close();
            $route.reload();
            // window.location.reload();
          } else {
            alert("同类型的时间段重叠！！");
            $route.reload();
            // window.location.reload();
          }

        }, function(data) {
          alert(data);
        });
    }

    $scope.cancel = function() {
      $modalInstance.dismiss("cancel");
    }
  })